package com.steven.ourcontest.main.view

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import android.widget.Toast.LENGTH_SHORT
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gyf.immersionbar.ImmersionBar
import com.steven.ourcontest.R
import com.steven.ourcontest.app.AppRouter
import com.steven.ourcontest.base.BaseActivity
import com.steven.ourcontest.base.BaseFragment
import com.steven.ourcontest.chat.bean.WSAccountBan
import com.steven.ourcontest.chat.bean.WSApplyFriendResponse
import com.steven.ourcontest.contest.view.ContestFragment
import com.steven.ourcontest.forum.view.ForumFragment
import com.steven.ourcontest.information.viewmodel.IdentifyViewModel
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.main.widget.MainTabBar.Companion.TAB_FORUM
import com.steven.ourcontest.main.widget.MainTabBar.Companion.TAB_MAIN
import com.steven.ourcontest.main.widget.MainTabBar.Companion.TAB_ME
import com.steven.ourcontest.chat.widget.OnSelectListener
import com.steven.ourcontest.main.widget.MainTabBar.Companion.TAB_CONTEST
import com.steven.ourcontest.me.view.MeFragment
import com.steven.ourcontest.net.NetConstants
import com.steven.ourcontest.net.websocket.WebSocketAndroidClient
import com.steven.ourcontest.utils.RxBus
import com.steven.ourcontest.utils.plusAssign
import com.steven.ourcontest.utils.toast
import kotlinx.android.synthetic.main.activity_main.*
import org.java_websocket.handshake.ServerHandshake

class MainActivity : BaseActivity() {

    private val mAdapter by lazy {
        AdapterFragmentPager(this)
    }
    private val identifyViewModel: IdentifyViewModel by viewModels()
    override fun getStatusBarColorString(): String? {
        return "#185dd1"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (LoginController.userId != 0L) {
            identifyViewModel.queryIdentifyStatus(LoginController.userId)
        }
    }

    override fun getViewId(): Int? {
        return R.layout.activity_main
    }

    override fun initView() {
        pager_main?.adapter = mAdapter
        pager_main?.isUserInputEnabled = false
        main_bar?.selectListener = object : OnSelectListener {
            override fun onSelected(current: Int, index: Int): Boolean {
                if (!LoginController.isLogin && (index == TAB_ME || index == TAB_CONTEST)) {
                    AppRouter.gotoLoginActivity(this@MainActivity, "me")
                    return false
                }
                when (index) {
                    TAB_MAIN -> {
                        ImmersionBar.with(this@MainActivity)
                            .statusBarColor("#185dd1")
                            .autoDarkModeEnable(true)
                            .init()
                    }
                    TAB_CONTEST -> {
                        ImmersionBar.with(this@MainActivity)
                            .statusBarColor(R.color.app_base)
                            .autoDarkModeEnable(true)
                            .init()
                    }
                    TAB_FORUM -> {
                        ImmersionBar.with(this@MainActivity)
                            .statusBarColor(R.color.main)
                            .autoDarkModeEnable(true)
                            .init()
                    }
                    TAB_ME -> {
                        ImmersionBar.with(this@MainActivity)
                            .statusBarColor("#89EEEE")
                            .autoDarkModeEnable(true)
                            .init()
                    }
                }
                pager_main?.setCurrentItem(index, false)
                return true
            }
        }
        identifyViewModel.identifyStatus.observe(this, Observer {
            if (it?.status == 2) {
                LoginController.userType = it.userType
            }
        })
        disposables += RxBus.getInstance()
            .toObservable(this, WSAccountBan::class.java).subscribe {
                if (it.data) {
                    toast("很遗憾，该账号已被封禁！", Toast.LENGTH_LONG)
                    LoginController.logout(this)
                }
            }
    }

    override fun onResume() {
        super.onResume()
        pager_main?.offscreenPageLimit = 4
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val action = intent?.getStringExtra("action")
        when (action) {
            "me" -> {
                main_bar?.setCurrentItem(TAB_ME)
            }
            "logout" -> {
                try {
                    mAdapter.fragments.forEach {
                        it.logout()
                    }
                    main_bar?.setCurrentItem(TAB_MAIN)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 100) {
            val action = data?.getStringExtra("action")
            when (action) {
                "loginSuccess" -> {
                    Toast.makeText(this, "登录成功", LENGTH_SHORT).show()
                    WebSocketAndroidClient.init(
                        this,
                        NetConstants.CHAT_WS_BASE_URL + LoginController.userId,
                        10000
                    )
                    WebSocketAndroidClient.getInstance()?.uri = NetConstants.CHAT_WS_BASE_URL + LoginController.userId
                    WebSocketAndroidClient.getInstance()
                        ?.connect(object : WebSocketAndroidClient.OnWebSocketOpenListener {
                            override fun onOpen(handshakedata: ServerHandshake?) {
                                Log.d("WebSocket", "连接成功")
                            }
                        })
                    if (LoginController.userId != 0L) {
                        identifyViewModel.queryIdentifyStatus(LoginController.userId)
                    }
                    mAdapter.fragments.forEach {
                        it.login()
                    }
                }
            }
        }
    }
}

class AdapterFragmentPager(fragmentActivity: FragmentActivity) :
    FragmentStateAdapter(fragmentActivity) {

    val fragments: ArrayList<BaseFragment> = ArrayList()

    init {
        fragments.add(MainFragment())
        fragments.add(ContestFragment())
        fragments.add(ForumFragment())
        fragments.add(MeFragment())
    }

    override fun createFragment(position: Int): Fragment {
        return fragments[position]
    }

    override fun getItemCount(): Int {
        return fragments.size
    }
}